package com.future.mayi.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.constant.AppCst;
import com.future.mayi.dialog.CommonDialog;
import com.future.mayi.dialog.EdtPasswordDialog;
import com.future.mayi.model.GoodsOrderModel;
import com.future.mayi.model.NewGoodsOrderModel;
import com.future.mayi.model.OrderAddModel;
import com.future.mayi.model.WxPayModel;
import com.future.mayi.response.GoodsOrderInfoResponse;
import com.future.mayi.response.MyIndexResponse;
import com.future.mayi.response.OrderAddResponse;
import com.future.mayi.utils.PayResult;
import com.future.mayi.utils.PriceUtils;
import com.future.mayi.utils.SharedPreferencesUtils;
import com.future.mayi.view.PasswordView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PayActivity extends BaseTitleActivity implements PasswordView.PasswordListener {
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_ali_pay)
    TextView tvAliPay;
    @BindView(R.id.tv_weixin_pay)
    TextView tvWeixinPay;
    @BindView(R.id.tv_wallet_pay)
    TextView tvWalletPay;

    @BindView(R.id.tv_enter)
    TextView tvEnter;

    private double money;
    //1-支付宝 2-微信 3-余额
    private int selectPay;
    private IWXAPI wxApi;

    private NewGoodsOrderModel newGoodsOrderModel;

    private String orderId;
    private String json;
    private String goodsId;


    public static void startActivity(Activity activity, NewGoodsOrderModel newGoodsOrderModel, double money) {
        Intent intent = new Intent(activity, PayActivity.class);
        intent.putExtra("newGoodsOrderModel", newGoodsOrderModel);
        intent.putExtra("money", money);
        activity.startActivityForResult(intent, 215);
    }


    public static void startActivity(Activity activity, String goodsId, String json, double money) {
        Intent intent = new Intent(activity, PayActivity.class);
        intent.putExtra("json", json);
        intent.putExtra("money", money);
        intent.putExtra("goodsId", goodsId);
        activity.startActivityForResult(intent, 215);
    }


    public static void startActivity(Activity activity, String orderId, double money) {
        Intent intent = new Intent(activity, PayActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("money", money);
        activity.startActivityForResult(intent, 215);
    }


    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("选择支付方式");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_pay);
    }

    @Override
    protected void initView() {
        setSelectPay(1);
    }

    @Override
    protected void initDates() {


        if (getIntent() != null) {
            money = getIntent().getDoubleExtra("money", 0);
            newGoodsOrderModel = getIntent().getSerializableExtra("newGoodsOrderModel") == null ? null : (NewGoodsOrderModel) getIntent().getSerializableExtra("newGoodsOrderModel");
            orderId = getIntent().getStringExtra("orderId");
            json = getIntent().getStringExtra("json");
            goodsId = getIntent().getStringExtra("goodsId");
        }
        tvMoney.setText("¥".concat(PriceUtils.getPriceText2(money)));

        tvWalletPay.setText("余额支付(余额:¥" + PriceUtils.getPriceText2(new Float((float) SharedPreferencesUtils.get(getActivity(), SharedPreferencesUtils.SpEnum.WalletBalance, 0f)).doubleValue()) + ")");


    }

    @Override
    protected void initListener() {
    }


    @OnClick({R.id.tv_ali_pay, R.id.tv_weixin_pay, R.id.tv_wallet_pay, R.id.tv_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ali_pay:
                setSelectPay(1);
                break;
            case R.id.tv_weixin_pay:
                setSelectPay(2);
                break;
            case R.id.tv_wallet_pay:
                setSelectPay(3);
                break;
            case R.id.tv_enter:
                tvEnter.setEnabled(false);
                if (!TextUtils.isEmpty(orderId)) {
                    payOrderById(orderId, null);
                } else if (newGoodsOrderModel != null) {
                    payNewGoodsOrder(null);
                } else if (json != null) {
                    payNewGoodsJson(null);
                }
                tvEnter.setEnabled(true);
                break;
        }
    }

    /**
     * 支付商品订单
     */
    private void payNewGoodsJson(String pay_pwd) {
        if (selectPay == 3 && pay_pwd == null) {
            payBuyWallet();
            return;
        }
        showLoadingDialog();
        new HttpRequest<OrderAddResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .addParam("goods_id", goodsId)
                .addParam("pay_type", selectPay)
                .addParam("order_info", json)
                .addParam("is_new", 2)
                .addParam("paypwd", pay_pwd)
                .setApiCode(ApiCst.multiAdd)
                .setListener(new HttpRequest.OnNetworkListener<OrderAddResponse>() {
                    @Override
                    public void onSuccess(OrderAddResponse response) {
                        dissmissLoadingDialog();
                        //1-支付宝 2-微信 3-余额 4-银联 10-分期
                        if (response.getOrderAddModel() == null) {
                            toast("提交订单失败");
                            return;
                        }
                        pay(response.getOrderAddModel());
                    }

                    @Override
                    public void onFail(String message, OrderAddResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .start(new OrderAddResponse());
    }


    /**
     * 支付商品订单
     */
    private void payNewGoodsOrder(String pay_pwd) {
        newGoodsOrderModel.setPay_type(selectPay);
        if (selectPay == 3 && pay_pwd == null) {
            payBuyWallet();
            return;
        }
        showLoadingDialog();
        new HttpRequest<OrderAddResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .addParam("address_id", newGoodsOrderModel.getAddress_id())
                .addParam("memo", newGoodsOrderModel.getNote())
                .addParam("is_cart", newGoodsOrderModel.getIs_cart())
                .addParam("pay_type", newGoodsOrderModel.getPay_type())
                .addParam("cart_ids", newGoodsOrderModel.getIs_cart() == 1 ? newGoodsOrderModel.getCart_ids() : null)
                .addParam("goods_id", newGoodsOrderModel.getIs_cart() == 0 ? newGoodsOrderModel.getGoods_id() : null)
                .addParam("goods_num", newGoodsOrderModel.getIs_cart() == 0 ? newGoodsOrderModel.getBuy_num() : null)
                .addParam("goods_spec_id", newGoodsOrderModel.getIs_cart() == 0 ? newGoodsOrderModel.getGoods_spec_id() : null)
                .addParam("paypwd", pay_pwd)
                .addParam("is_new", 2)

                .setApiCode(ApiCst.orderAdd)
                .setListener(new HttpRequest.OnNetworkListener<OrderAddResponse>() {
                    @Override
                    public void onSuccess(OrderAddResponse response) {
                        dissmissLoadingDialog();
                        //1-支付宝 2-微信 3-余额 4-银联 10-分期
                        if (response.getOrderAddModel() == null) {
                            toast("提交订单失败");
                            return;
                        }
                        newGoodsOrderModel = null;
                        pay(response.getOrderAddModel());
                    }

                    @Override
                    public void onFail(String message, OrderAddResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .start(new OrderAddResponse());
    }

    private void payOrderById(String order_id, String pay_pwd) {
        if (selectPay == 3 && TextUtils.isEmpty(pay_pwd)) {
            payBuyWallet();
            return;
        }
        new HttpRequest<OrderAddResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", order_id)
                .addParam("pay_type", selectPay)
                .addParam("pay_pwd", selectPay == 3 ? pay_pwd : null)
                .setApiCode(ApiCst.payOrder)
                .setListener(new HttpRequest.OnNetworkListener<OrderAddResponse>() {
                    @Override
                    public void onSuccess(OrderAddResponse response) {
                        dissmissLoadingDialog();
                        //1-支付宝 2-微信
                        if (response.getOrderAddModel() == null) {
                            toast("提交订单失败");
                            return;
                        }
                        pay(response.getOrderAddModel());
                    }

                    @Override
                    public void onFail(String message, OrderAddResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .start(new OrderAddResponse());
    }


    private void pay(OrderAddModel orderAddModel) {
        orderId = String.valueOf(orderAddModel.getOrder_id());
        money = orderAddModel.getPay_price();
        wxPay = false;
        //1-支付宝 2-微信
        switch (selectPay) {
            case 1:
                payBuyAliPay(orderAddModel.getAlipay_info());
                break;
            case 2:
                payBuyWechatPay(orderAddModel.getWx_pay_info());
                break;
            case 3:
                paySuccess();
                break;
        }
    }


    // ----------------------------------------------------阿里支付-------------------------------------------------------

    private static final int SDK_PAY_FLAG = 1;

    private void payBuyAliPay(final String orderInfo) {
        if (TextUtils.isEmpty(orderInfo)) {
            toast("订单支付失败");
            return;
        }

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                pHandler.sendMessage(msg);
            }
        };


        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler pHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        paySuccess();
                    } else {
                        payError();
                    }
                }
                break;
                default:
                    break;
            }
        }

        ;
    };
    // ----------------------------------------------------阿里支付-------------------------------------------------------


    // ----------------------------------------------------微信支付-------------------------------------------------------
    private boolean wxPay;

    private void payBuyWechatPay(WxPayModel model) {
        wxPay = true;
        PayReq req = new PayReq();
        req.appId = model.getAppid();
        req.partnerId = model.getPartnerid();
        req.prepayId = model.getPrepayid();
        req.nonceStr = model.getNoncestr();
        req.timeStamp = model.getTimestamp();
        req.sign = model.getSign();
        req.extData = "app data";
        req.packageValue = model.getPackageX();
        //发起支付请求
        wxApi.sendReq(req);
    }
    // ----------------------------------------------------微信支付-------------------------------------------------------


    private void setSelectPay(int selectPay) {
        if (selectPay == this.selectPay) return;
        this.selectPay = selectPay;
        if (selectPay == 2 && wxApi == null) {
            wxApi = WXAPIFactory.createWXAPI(this, AppCst.Wechat_APP_ID);
        }
        setSelectPayTextView(selectPay == 1, tvAliPay);
        setSelectPayTextView(selectPay == 2, tvWeixinPay);
        setSelectPayTextView(selectPay == 3, tvWalletPay);
    }

    private void setSelectPayTextView(boolean select, TextView textView) {
        Drawable drawableLeft = null;
        if (textView == tvAliPay)
            drawableLeft = getResources().getDrawable(R.drawable.zhifu_zhifubao);
        if (textView == tvWeixinPay)
            drawableLeft = getResources().getDrawable(R.drawable.zhifu_weiixn);
        if (textView == tvWalletPay)
            drawableLeft = getResources().getDrawable(R.drawable.zhifu_qianbao);
        if (drawableLeft != null)
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
        Drawable drawableRight = select ? getResources().getDrawable(R.drawable.img_select_t) : getResources().getDrawable(R.drawable.img_select_f);
        drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());
        textView.setCompoundDrawables(drawableLeft, null, drawableRight, null);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private void payCancel() {
        toast("支付取消");
    }

    private void payError() {
        toast("支付失败");
    }

    private void paySuccess() {
        toast("支付成功");
        Intent intent = new Intent(this, PaySuccessActivity.class);
        intent.putExtra("orderId", orderId);
        startActivity(intent);
        this.finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (wxPay) {
            wxPay = false;
            int code = (int) SharedPreferencesUtils.get(this, SharedPreferencesUtils.SpEnum.WxPayResp, 999);
            if (code == 0) {
                paySuccess();
            } else if (code == -1) {
                payError();
            } else if (code == -2) {
                payCancel();
            } else {
                getOrderStates();
            }
            SharedPreferencesUtils.set(this, SharedPreferencesUtils.SpEnum.WxPayResp, 999);
        } else getBalance();
    }


    private void getOrderStates() {
        showLoadingDialog();
        new HttpRequest<GoodsOrderInfoResponse>()
                .with(this).setApiCode(ApiCst.getOrderDetail)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .setListener(new HttpRequest.OnNetworkListener<GoodsOrderInfoResponse>() {
                    @Override
                    public void onSuccess(GoodsOrderInfoResponse response) {
                        dissmissLoadingDialog();
                        GoodsOrderModel model = response.model;
                        if (model.getStatus() != 0) {
                            paySuccess();
                        }
                    }

                    @Override
                    public void onFail(String message, GoodsOrderInfoResponse response) {
                        toast(message);
                    }
                }).start(new GoodsOrderInfoResponse());
    }

    private void getBalance() {
        new HttpRequest<MyIndexResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.myIndex)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<MyIndexResponse>() {

                    @Override
                    public void onSuccess(MyIndexResponse response) {
                        tvWalletPay.setText("余额支付(余额:¥" + PriceUtils.getPriceText2(response.userInfoModel.getMoney()) + ")");
                    }

                    @Override
                    public void onFail(String message, MyIndexResponse response) {

                    }
                }).start(new MyIndexResponse());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String msg = "";
        String str = data.getExtras().getString("pay_result");
        System.out.println("str=========>" + str);
        if (str.equalsIgnoreCase("success")) {

        } else if (str.equalsIgnoreCase("fail")) {
            payError();
        } else if (str.equalsIgnoreCase("cancel")) {
            toast(" 你已取消了本次订单的支付！ ");
        }
    }


    // ----------------------------------------------------钱包支付-------------------------------------------------------
    private EdtPasswordDialog edtPasswordDialog;

    private boolean IsSetPayPwd = false;

    private void payBuyWallet() {
        if (!IsSetPayPwd) {
            new HttpRequest<DefaultResponse>()
                    .with(this)
                    .addParam("token", App.getToken(mContext))
                    .setApiCode(ApiCst.isSetPayPwd)
                    .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                        @Override
                        public void onSuccess(DefaultResponse response) {
                            IsSetPayPwd = true;
                            dissmissLoadingDialog();
                            payBuyWallet();
                        }

                        @Override
                        public void onFail(String message, DefaultResponse response) {
                            showSetPayPswTip();
                            dissmissLoadingDialog();
                        }
                    })
                    .start(new DefaultResponse());
            return;
        }

        if (edtPasswordDialog != null) edtPasswordDialog.dismiss();
        edtPasswordDialog = new EdtPasswordDialog(this);
        edtPasswordDialog.show();
        edtPasswordDialog.setListener(this);
    }

    private void showSetPayPswTip() {
        new CommonDialog.Builder(this)
                .setCancelable(false)
                .setMessage("暂未设置支付密码，请先设置支付密码")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(new Intent(PayActivity.this, SettingPayPasswordActivity.class));
                    }
                }).show();
    }

    @Override
    public void passwordChange(String changeText) {
    }

    @Override
    public void passwordComplete() {
    }

    @Override
    public void keyEnterPress(String password, boolean isComplete) {
        if (isComplete) {
            edtPasswordDialog.dismiss();
            if (!TextUtils.isEmpty(orderId)) {
                payOrderById(orderId, password);
            } else if (newGoodsOrderModel != null) {
                payNewGoodsOrder(password);
            } else if (json != null) {
                payNewGoodsJson(password);
            }
        }
    }


    // ----------------------------------------------------钱包支付-------------------------------------------------------

}
